import NextAuth from "next-auth";
import authConfig from "./auth.config";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { db } from "./lib/db";
import { getUserById } from "./data/user";
import { UserRole } from "@prisma/client";
import { getTwoFactoryConfirmationByUserId } from "./data/two-factory-confirmation";
export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth(() => {
  return {
    pages: {
      signIn: "/auth/login",
      error: "/auth/error",
    },
    events: {
      async linkAccount({ user }) {
        await db.user.update({
          where: { id: user.id },
          data: {
            emailVerified: new Date(),
          },
        });
      },
    },
    callbacks: {
      async signIn({ user, account }) {
        if (account?.provider !== "credentials") return true;

        const existingUser = await getUserById(user.id!);
        if (!existingUser) return false;

        const { emailVerified, isEmailVerified } = existingUser;
        if (isEmailVerified) {
          const existingTwoFactoryConfirmation =
            getTwoFactoryConfirmationByUserId(existingUser.id);
          if (!existingTwoFactoryConfirmation) return false;
        }

        if (!emailVerified && !isEmailVerified) return false;
        return true;
      },
      session({ session, token }) {
        if (token.sub && session.user) {
          session.user.id = token.sub;
        }
        if (token.role && session.user) {
          session.user.role = token.role as UserRole;
        }
        return session;
      },
      async jwt({ token }) {
        if (!token.sub) return token;
        const existingUser = await getUserById(token.sub);
        if (!existingUser) return token;
        token.role = existingUser.role;
        return token;
      },
    },
    adapter: PrismaAdapter(db),
    session: { strategy: "jwt" },
    ...authConfig,
  };
});
